import axios from "axios";
import store from "@/store";
import funTool from "./funTool";
import config from "@/config";

const axiosLoad = {
  show: () => {
    let loadWarp = document.getElementById("load-warp");
    if (loadWarp) {
      loadWarp.style.display = "block";
    }
  },
  hide: () => {
    let loadWarp = document.getElementById("load-warp");
    if (loadWarp) {
      loadWarp.style.display = "none";
    }
  }
};

class Http {
  static baseUrl() {
    return config.apiUrl;
  }

  static ImgSrc(src) {
    return Http.baseUrl() + src;
  }

  static getHttpInstance(config) {
    let defaultConfig = {
      timeout: 300000,
      // withCredentials: true,
      headers: {},
      baseURL: Http.baseUrl(),
      dataponseType: "json", // default
      transformdataponse: [
        function(data) {
          // 在这里根据自己的需求改变数据
          return data;
        }
      ]
    };
    let newConfig = Object.assign({}, defaultConfig, config);

    newConfig.headers["admin-token"] = store.state.user.token;

    let instance = axios.create(newConfig);

    // 请求过滤
    instance.interceptors.request.use(
      config => {
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    // 响应过滤
    instance.interceptors.response.use(
      response => {
        if (response.status === 200) {
          if (response.data && response.data.code === 0) {
            return response;
          } else {
            axiosLoad.hide();
            let msg = response.data.message;
            window.rootVue.$Message.error({ content: msg, duration: 3 });
            return Promise.reject(msg);
          }
        } else {
          axiosLoad.hide();
          return Promise.reject(error);
        }
      },
      error => {
        axiosLoad.hide();

        if (error && error.response && error.response.status === 401) {
          store.commit("user/setToken", "");
          window.rootVue.$router.push({
            name: "login" // 跳转到homeName页
          });
          return Promise.reject(error);
        }

        let msg = error.message;
        if (msg.indexOf("Network Error") > -1) {
          msg = "网络错误，请刷新后重试";
        } else if (msg.indexOf("timeout of") > -1) {
          msg = "请求超时，请稍后后重试";
        }
        window.rootVue.$Message.error({ content: msg, duration: 3 });
        return Promise.reject(error);
      }
    );

    return instance;
  }

  static formatParamete(param) {
    param = param || {};

    // param = funTool.removeEmptyObject(param);

    // 格式化时间字符串
    if (param) {
      for (let key in param) {
        if (param[key] && param[key].getFullYear) {
          param[key] = funTool.formatDate(param[key], "YYYY-MM-DD HH:mm:ss");
        }
      }
    }

    param = JSON.parse(JSON.stringify(param));

    return param;
  }

  // 格式化FormData参数
  static formatFormDataParam(param) {
    let formData = new FormData();

    Object.keys(param).forEach(key => {
      formData.append(key, param[key]);
    });

    return formData;
  }

  async get(url, param, config) {
    let instance = Http.getHttpInstance();
    param = Http.formatParamete(param);
    let promise = new Promise(function(resolve, reject) {
      if (!config || !config.hideLoad) {
        axiosLoad.show();
      }

      instance.get(url, { params: param }).then(async respnose => {
        axiosLoad.hide();
        resolve(respnose.data);
      });
    });

    return promise;
  }

  async postFormData(url, data) {
    let instance = Http.getHttpInstance({
      headers: { "Content-Type": "application/x-www-form-urlencoded" }
    });
    let param = Http.formatFormDataParam(data);
    let promise = new Promise(function(resolve, reject) {
      instance.post(url, param).then(respnose => {
        axiosLoad.hide();
        resolve(respnose.data);
      });
    });
    return promise;
  }

  async post(url, param, config) {
    let instance = Http.getHttpInstance(config);
    param = Http.formatParamete(param);

    let promise = new Promise(function(resolve, reject) {
      if (!config || !config.hideLoad) {
        axiosLoad.show();
      }

      instance.post(url, param).then(respnose => {
        axiosLoad.hide();
        resolve(respnose.data);
      });
    });

    return promise;
  }

  async fileExport(url, param) {
    let formData = Http.formatFormDataParam(param);

    let config = {
      headers: {
        "admin-token": store.state.user.token,
        "Content-Type": "application/json"
      },
      baseURL: Http.baseUrl(),
      url: url,
      responseType: "blob"
    };
    let res = await axios.post(url, formData, config);
    const filename = res.headers.filename;
    const a = document.createElement("a");
    const href = window.URL.createObjectURL(res.data);
    a.href = href;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
  }
}

const http = new Http();

export default http;
